package cn.xspace.chatui.view;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.PowerManager;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hyphenate.EMError;
import com.xspace.android.xafcommon.util.AppConstant;
import com.xspace.android.xafcommon.util.AppUtils;

import java.io.File;

import cn.xspace.chatui.R;
import cn.xspace.chatui.util.VoiceRecorder;
import cn.xspace.chatui.view.chat.EaseChatRowVoicePlayClickListener;

/**
 * Created by liuchen on 2016/10/31.
 */

public class RecordDialog extends Dialog {

    public static final String VOICENAME = "voiceName";
    public static final String VOICEPATH = "voicePath";
    public static final String VOICETIME = "voiceTime";
    private LinearLayout mLinear_logo;
    private ImageView mImg_left;
    private ImageView mImg_center;
    private ImageView mImg_right;
    private TextView mTextview_press_say;

    private Context mContext;
    protected VoiceRecorder voiceRecorder;

    protected PowerManager.WakeLock wakeLock;

    IRecordComplete iRecordComplete;

    @SuppressWarnings("deprecation")
    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);

    }

    public RecordDialog(Context context, int theme, String strMessage) {
        super(context, theme);
        mContext = context;
        this.setContentView(R.layout.dialog_record);
        this.setCanceledOnTouchOutside(true);
        this.setCancelable(true);
        findView();
        init();
        setListener();
    }

    public void setiRecordComplete(IRecordComplete iRecordComplete) {
        this.iRecordComplete = iRecordComplete;
    }

    private void findView() {
        mLinear_logo = (LinearLayout) findViewById(R.id.linear_logo);
        mImg_left = (ImageView) findViewById(R.id.img_left);
        mImg_center = (ImageView) findViewById(R.id.img_center);
        mImg_right = (ImageView) findViewById(R.id.img_right);
        mTextview_press_say = (TextView) findViewById(R.id.textview_press_say);
    }

    private void setListener() {
        mTextview_press_say.setOnTouchListener(new View.OnTouchListener() {

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return onPressToSpeakBtnTouch(v, event);
            }
        });
        setOnDismissListener(new OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                if (voiceRecorder != null) {
                    voiceRecorder.discardRecording();
                }
            }
        });
    }


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        if (!hasFocus) {
            dismiss();
        }
    }

    protected Handler micImageHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            // change image
//            micImage.setImageDrawable(micImages[msg.what]);
        }
    };

    private void initDir() {
        File file = new File(AppConstant.FILE_ADDRESS);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    private void init() {
        initDir();
        wakeLock = ((PowerManager) mContext.getSystemService(Context.POWER_SERVICE)).newWakeLock(
                PowerManager.SCREEN_DIM_WAKE_LOCK, "demo");
        voiceRecorder = new VoiceRecorder(micImageHandler);
    }


    public void showReleaseToCancelHint() {
        mTextview_press_say.setText(mContext.getString(R.string.release_to_cancel));

    }

    public void showMoveUpToCancelHint() {
        mTextview_press_say.setText(mContext.getString(R.string.move_up_to_cancel));

    }

    /**
     * 显示圈圈
     */
    public void showDialog() {
        if (!isShowing()) {
            show();
        }
    }

    public boolean onPressToSpeakBtnTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                try {
                    if (EaseChatRowVoicePlayClickListener.isPlaying)
                        EaseChatRowVoicePlayClickListener.currentPlayListener.stopPlayVoice();
//                    v.setPressed(true);
//                    beforeRecording();
                    startRecording();
                } catch (Exception e) {
                    v.setPressed(false);
                }
                return true;
            case MotionEvent.ACTION_MOVE:
                if (event.getY() < 0) {
                    showReleaseToCancelHint();
                } else {
                    showMoveUpToCancelHint();
                }
                return true;
            case MotionEvent.ACTION_UP:
                dismiss();
                if (event.getY() < 0) {
                    // discard the recorded audio.
                    discardRecording();
                } else {
                    // stop recording and send voice file
                    try {
                        int length = stopRecoding();

                        if (length > 0) {
                            if (iRecordComplete != null) {
                                iRecordComplete.recordSuccess(getVoiceFilePath(), getVoiceFileName(), length);
                            }
                            dismiss();
//                            if (recorderCallback != null) {
//                                recorderCallback.onVoiceRecordComplete(getVoiceFilePath(), length);
//                            }
//                            Intent intent = new Intent();
//                            intent.putExtra(VOICEPATH, getVoiceFilePath());// 把返回数据存入Intent
////                            int time = (int) ((mEndRecodingTime - mStartRecodingTime) / 1000);
////                            String voiceTime = time + "";
//                            intent.putExtra(VOICETIME, length);// 把返回数据存入Intent
//                            setResult(RESULT_OK, intent);
//                            finish();
                        } else if (length == EMError.FILE_INVALID) {
                            Toast.makeText(mContext, R.string.Recording_without_permission, Toast.LENGTH_SHORT).show();
                            iRecordComplete.recordFail();
                        } else {
                            Toast.makeText(mContext, R.string.The_recording_time_is_too_short, Toast.LENGTH_SHORT)
                                    .show();
                            iRecordComplete.recordFail();
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Toast.makeText(mContext, R.string.send_failure_please, Toast.LENGTH_SHORT).show();
                        iRecordComplete.recordFail();
                    }
                }
                return true;
            default:
                return false;
        }
    }

    public void startRecording() {
        if (!AppUtils.isSdcardExist()) {
            Toast.makeText(mContext, R.string.Send_voice_need_sdcard_support, Toast.LENGTH_SHORT).show();
            return;
        }
        try {
            wakeLock.acquire();
//            this.setVisibility(View.VISIBLE);
            mTextview_press_say.setText(mContext.getString(R.string.move_up_to_cancel));
//            recordingHint.setBackgroundColor(Color.TRANSPARENT);
            voiceRecorder.startRecording(mContext);
        } catch (Exception e) {
            e.printStackTrace();
            if (wakeLock.isHeld())
                wakeLock.release();
            if (voiceRecorder != null)
                voiceRecorder.discardRecording();
//            this.setVisibility(View.INVISIBLE);
            Toast.makeText(mContext, R.string.recoding_fail, Toast.LENGTH_SHORT).show();
            return;
        }
    }

    public void discardRecording() {
        if (wakeLock.isHeld())
            wakeLock.release();
        try {
            // stop recording
            if (voiceRecorder.isRecording()) {
                voiceRecorder.discardRecording();
//                this.setVisibility(View.INVISIBLE);
            }
        } catch (Exception e) {
        }
    }

    /**
     * 不显示圈圈
     */
    public void dismissProgress() {
        if (isShowing()) {
            dismiss();
        }
    }

    public int stopRecoding() {
//        this.setVisibility(View.INVISIBLE);
        if (wakeLock.isHeld())
            wakeLock.release();
        return voiceRecorder.stopRecoding();
    }

    public String getVoiceFilePath() {
        return voiceRecorder.getVoiceFilePath();
    }

    public String getVoiceFileName() {
        return voiceRecorder.getVoiceFileName();
    }

    public boolean isRecording() {
        return voiceRecorder.isRecording();
    }

    public static class Builder {
        RecordDialog mRecordDialog;

        public Builder(Context context, int theme) {
            mRecordDialog = new RecordDialog(context, theme, "");
        }

        public Builder(Context context) {
            this(context, R.style.CustomDialog);
        }

        public RecordDialog.Builder setListener(IRecordComplete listener) {
            mRecordDialog.setiRecordComplete(listener);
            return this;
        }

        public void show() {
            mRecordDialog.show();
        }
    }

    public interface IRecordComplete {
        void recordSuccess(String path, String name, int length);

        void recordFail();
    }


}
